package com.firefly.service.command.cms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.firefly.dao.dao.cms.po.ArticlePo;
import com.firefly.dao.dao.cms.po.CateRelationPo;
import com.firefly.dao.dao.cms.po.CategoryPo;
import com.firefly.dao.dao.cms.service.ArticleService;
import com.firefly.dao.dao.cms.service.CateRelationService;
import com.firefly.util.handle.FireflyException;
import com.firefly.dao.assembler.cms.CategoryAssembler;
import com.firefly.dao.dto.CommonDto;
import com.firefly.dao.dto.cms.CategoryDto;
import com.firefly.dao.dto.cms.CategorySortDto;
import com.firefly.service.repository.cms.CategoryRelationRepository;
import com.firefly.service.repository.cms.CategoryRepository;
import com.firefly.util.utils.FuncUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 栏目
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/12/20
 **/
@Service
public class CategoryCommand {
    private final CategoryAssembler categoryAssembler;
    private final CategoryRepository categoryRepository;
    private final CategoryRelationRepository categoryRelationRepository;
    private final CateRelationService cateRelationService;
    private final ArticleService articleService;
    @Autowired
    public CategoryCommand(CategoryAssembler categoryAssembler,CategoryRepository categoryRepository,CategoryRelationRepository categoryRelationRepository,CateRelationService cateRelationService,ArticleService articleService){
        this.categoryAssembler = categoryAssembler;
        this.categoryRepository = categoryRepository;
        this.categoryRelationRepository = categoryRelationRepository;
        this.cateRelationService = cateRelationService;
        this.articleService = articleService;
    }

    @Transactional
    public Boolean create(CategoryDto request) {
        Integer parentId = request.getParentId();
        CategoryPo entity = categoryAssembler.getPo(request);
        // 生成url
        FuncUtils f = new FuncUtils();
        String url = f.getUUIDString();
        entity.setUrl(url);
        Integer id = categoryRepository.create(entity);
        // 自引用关系
        this.updateRelation(id,parentId);
        return true;
    }

    @Transactional
    public Boolean update(CategoryDto request) {
        Integer parentId = request.getParentId();
        Integer id = request.getId();
        if (id == parentId){
            throw new FireflyException(403, "不能选择自己为父级");
        }
        CategoryPo entity = categoryAssembler.getPo(request);
        Boolean result = categoryRepository.update(entity);
        // 清除父栏目id
        categoryRelationRepository.removeByDescendant(id);
        // 自引用关系
        this.updateRelation(id,parentId);
        return result;
    }
    public Boolean updateSort(CategorySortDto request){
        return categoryRepository.updateSortById(request.getId(), request.getSort());
    }
    @Transactional
    public Boolean remove(CommonDto request) {
        // 查所有子栏目id
        QueryWrapper<CateRelationPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ancestor", request.detailId);
        List<CateRelationPo> list = cateRelationService.list(queryWrapper);
        List<Integer> ids = list.stream().map((CateRelationPo c) -> c.getDescendant()).toList();
        // 栏目下是否有文章
        QueryWrapper<ArticlePo> articlesQueryWrapper = new QueryWrapper<>();
        articlesQueryWrapper.in("cate_id",ids).eq("del_flag",0);
        if (articleService.count(articlesQueryWrapper) > 0){
            throw new FireflyException(403, "栏目下有文章，不可删除");
        }
        // 删除栏目及关联关系
        categoryRelationRepository.removeByDescendants(ids);
        return categoryRepository.removeByIds(ids);
    }

    private void updateRelation(Integer id,Integer parentId){
        List<CateRelationPo> insert = new ArrayList<>();
        CateRelationPo parent1 = new CateRelationPo();
        parent1.setAncestor(id);
        parent1.setDescendant(id);
        parent1.setDistance(0);
        insert.add(parent1);
        if (parentId != 0) {
            QueryWrapper<CateRelationPo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("descendant", parentId);
            List<CateRelationPo> list = cateRelationService.list(queryWrapper);
            list.forEach(item -> {
                CateRelationPo tmp = new CateRelationPo();
                tmp.setAncestor(item.getAncestor());
                tmp.setDescendant(id);
                tmp.setDistance(item.getDistance() + 1);
                insert.add(tmp);
            });
        } else {
            CateRelationPo parent0 = new CateRelationPo();
            parent0.setAncestor(0);
            parent0.setDescendant(id);
            parent0.setDistance(1);
            insert.add(parent0);
        }
        // 增加最大层数判断，最小是2个（自己与顶级0）
        if ((insert.size() - 1) > 3){
            throw new FireflyException(403,"栏目层级最大为3级");
        }
        // 插入级别关系
        categoryRelationRepository.saveBatch(insert);
    }
}
